<template>
  <n-grid ref="progressGridRef" v-if="commonProgress.totalNum > 0">
    <n-grid-item :span="24">
      <n-space justify="space-around">
        <n-statistic label="当前进度" :value="commonProgress.successNum + commonProgress.failNum">
          <template #prefix>
          </template>
          <template #suffix>
            / {{ commonProgress.totalNum }}
          </template>
        </n-statistic>
        <n-statistic label="成功/失败">
          <template #prefix>
            {{ commonProgress.successNum }}
          </template>
          <template #suffix>
            /
            <n-gradient-text type="error">{{ commonProgress.failNum }}</n-gradient-text>
          </template>
        </n-statistic>
      </n-space>
    </n-grid-item>
    <n-grid-item :span="24">
      <n-progress
        type="line"
        :percentage=" Math.round(( (commonProgress.successNum + commonProgress.failNum) / commonProgress.totalNum) * 100) "
        :height="30"
        :border-radius="5"
        :fill-border-radius="0"
        :indicator-placement="'inside'"
        :processing="commonProgress.successNum + commonProgress.failNum < commonProgress.totalNum "
      />
      <n-h6>
        {{commonProgress.message}}
      </n-h6>
    </n-grid-item>

  </n-grid>
  <n-space v-else>
    {{commonProgress.message}}
  </n-space>
</template>

<script setup lang="ts">
import {onMounted, onUnmounted, ref} from "vue";
import {taskinfoController} from "@/api/controller/taskinfo/taskinfoController";

let timer = ref(null);
const maxQueryTime = 5 * 60 * 1000; // 60 seconds
let startTime = Date.now();
const commonProgress = ref({
  totalNum: 0,
  successNum: 0,
  failNum: 0,
  message: '正在获取进度,请稍等...'
})


const props = defineProps({
  taskId: {
    type: String,
    required: true
  }
})

onMounted(() => {
  timer.value = setInterval(() => {
    if (Date.now() - startTime > maxQueryTime || ( commonProgress.value.totalNum > 0 && commonProgress.value.failNum + commonProgress.value.successNum == commonProgress.value.totalNum)) {
      clearInterval(timer.value);
      timer.value = null;
    } else {
      getCommonProgress();
    }
  }, 1000);
})

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
})

const getCommonProgress = () => {
  taskinfoController.getCommonProgressInfo(props.taskId).then(res => {
    if (res.code == 200) {
      commonProgress.value = res.data
    }
  })
}
</script>
